package com.earthea.message.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.earthea.message.entity.domain.Message;
import com.earthea.message.mapper.MessageMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.ArrayList;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
public class MessageServiceImplTest {
    @InjectMocks
    private MessageServiceImpl messageService;

    @Mock
    private MessageMapper messageMapper;

    @Test
    public void selectAll() {
        // 构造数据
        int count = 10;
        int depth = 5;
        List<Message> messages = getMessages(count, depth);
        when(messageMapper.selectAll()).thenReturn(messages);
        // 执行
        long start = System.currentTimeMillis();
        List<Message> roots = messageService.selectAll();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        assertThat(roots.size()).isEqualTo(10);
        for (Message current : roots) {
            assertThat(current.getChildren().size()).isEqualTo(10);
        }
    }

    private List<Message> getMessages(int count, int depth) {
        List<Message> messages = new ArrayList<>();
        List<Message> result = new ArrayList<>();
        for (int i = 0; i < depth; i++) {
            List<Message> temp = getMessages(messages, count);
            result.addAll(temp);
            messages = temp;
        }
        return result;
    }

    private List<Message> getMessages(List<Message> preMessage, int count) {
        List<Message> messages = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(preMessage)) {
            long preMax = preMessage.stream().map(Message::getId).max(Long::compareTo).get();
            for (Message msg : preMessage) {
                for (long id = preMax + 1; id <= preMax + count; id++) {
                    messages.add(getMessage(id, msg.getId()));
                }
                preMax = preMax + count;
            }
        } else {
            for (long id = 0; id < count; id++) {
                messages.add(getMessage(id, -1L));
            }
        }
        return messages;
    }

    private Message getMessage(long id, long parentId) {
        Message message = new Message();
        message.setId(id);
        message.setContent("content" + id);
        message.setParentId(parentId);
        message.setUsername("username" + id);
        message.setCreateTime("2025-07-29 16:55:00");
        message.setUpdateTime("2025-07-29 16:55:00");
        return message;
    }
}